package edu.pku.sei.transformation.codegen;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;

import edu.pku.sei.transformation.editor.model.AtomicTransformation;
import edu.pku.sei.transformation.editor.model.execution.TransformationExecution;
import edu.pku.sei.transformation.editor.model.implement.ICodegenElement;
import edu.pku.sei.transformation.editor.model.implement.TransformationCode;

public abstract class TransformationExecutionCodegenAdapter extends CodegenAdapter {

	@Override
	public boolean canGenerate(ICodegenElement element) {
		if (element != null && element instanceof TransformationExecution) {
			TransformationExecution transExe = (TransformationExecution) element;
			if (transExe.getTransformation() != null && transExe.getTransformation() instanceof AtomicTransformation)
				return true;
			else
				return false;
		} else {
			return false;
		}
	}
	
	@Override
	public boolean generateCode(ICodegenElement element, boolean force) {
		if (!canGenerate(element)) {
			return false;
		} else {
			TransformationExecution transformation = (TransformationExecution) element;
			
			IFile file = null;
			TransformationCode code = transformation.getCode(getLanguage());
			
			//already have code
			if (code != null && code.getFile() != null) {
				file = code.getFile();
				//force generate
				if (force) {
					return generateCodeToFile(element, file);
				} else {
					return true;
				}
			} 
			//do not have code
			else {
				try {
					file = getFile(transformation, getFileName(element), getLanguage());
					if (file == null)
						return false;
				} catch (CoreException e1) {
					e1.printStackTrace();
					return false;
				}						
				code = transformation.addCode(getLanguage(), file.getLocation().toString());
				code.setFile(file);
				return generateCodeToFile(element, file);
			}
		}
	}
}
